package com.web.pay;

import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.web.pay.common.BaseActivity;
import com.web.pay.common.MultiItemDivider;
import com.web.pay.data.BGetCashRecord;
import com.web.pay.util.RequestUtils;

import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Type;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

public class ProfitActivity extends BaseActivity {
    private Button mBtnBack;
    private Button mBtnRefresh;
    private RecyclerView mRecyclerView;
    private MyAdapter mAdapter;

    private ArrayList<BGetCashRecord> mDataList;
    private Dialog mRejectDialog;
    private TextView mTextReason;
    private Dialog mPassDialog;
    private BGetCashRecord mPreCashRecord;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profit);

        init();
    }

    private void init() {
        mDataList = new ArrayList<>();

        mBtnBack = findViewById(R.id.btn_back);
        mBtnRefresh = findViewById(R.id.btn_refresh);
        mRecyclerView = findViewById(R.id.recycler);

        mBtnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        mBtnRefresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                requestGetCashRecordByUser();
            }
        });

        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));

        MultiItemDivider divider = new MultiItemDivider(this, DividerItemDecoration
                .VERTICAL,
                ContextCompat.getDrawable(this, R.drawable.shape_consume_history_recycler_divider));
        divider.setDividerMode(MultiItemDivider.INSIDE);
        mRecyclerView.addItemDecoration(divider);

        mAdapter = new MyAdapter();
        mRecyclerView.setAdapter(mAdapter);

        requestGetCashRecordByUser();
    }

    private class MyViewHolder extends RecyclerView.ViewHolder {
        public TextView textUniqueId;
        public TextView textMoney;
        public TextView textStatus;
        public TextView textReject;
        public TextView textStartTime;
        public TextView textEndTime;
        public TextView textAccount;
        public TextView btnUniqueIdCopy;
        public TextView btnAccountCopy;
        public View viewReject;
        public View viewEndTime;
        public Button btnReject;
        public Button btnPass;
        public TextView textUserName;
        public TextView textRequest;
        public View viewBtn;

        public MyViewHolder(View itemView) {
            super(itemView);

            textUniqueId = itemView.findViewById(R.id.text_unique_id);
            textMoney = itemView.findViewById(R.id.text_money);
            textEndTime = itemView.findViewById(R.id.text_end_time);
            textReject = itemView.findViewById(R.id.text_reject);
            textStartTime = itemView.findViewById(R.id.text_start_time);
            textStatus = itemView.findViewById(R.id.text_status);
            textAccount = itemView.findViewById(R.id.text_account);
            btnUniqueIdCopy = itemView.findViewById(R.id.btn_uniqueId_copy);
            btnAccountCopy = itemView.findViewById(R.id.btn_account_copy);
            viewEndTime = itemView.findViewById(R.id.relayout_end_time);
            viewReject = itemView.findViewById(R.id.relayout_reject);
            btnPass = itemView.findViewById(R.id.btn_pass);
            btnReject = itemView.findViewById(R.id.btn_reject);
            textUserName = itemView.findViewById(R.id.text_userName);
            textRequest = itemView.findViewById(R.id.text_request);
            viewBtn = itemView.findViewById(R.id.view_btn);
        }
    }

    private void requestGetCashRecordByUser() {
        getLoadingDialog().show();
        RequestUtils.getRequest(AppConst.Profit_Record_Url, new IHttpResponse() {
            @Override
            public void OnHttpData(final String data) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        getLoadingDialog().dismiss();
                        if(!isFinishing()) {
                            try{
                                JSONObject object = new JSONObject(data);
                                if(object.getInt("status") != 0) {
                                    //未成功
                                    Toast.makeText(getApplicationContext(),object.getString("msg"),Toast.LENGTH_SHORT).show();
                                    return;
                                }
                                String strData = object.getString("data");
                                Type type = new TypeToken<List<BGetCashRecord>>() {}.getType();
                                List<BGetCashRecord> result = new Gson().fromJson(strData,type);
                                if(result != null) {
                                    mDataList.clear();
                                    mDataList.addAll(result);
                                    mAdapter.notifyDataSetChanged();
                                }
                            }catch (Exception e) {
                                Log.e("yy",e.toString());
                            }
                        }
                    }
                });
            }

            @Override
            public void OnHttpDataError(final IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        getLoadingDialog().dismiss();
                        Toast.makeText(getApplicationContext(),e.toString(),Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    /**
     * 提交审核结果
     * @param cashRecord
     */
    private void requestCommitCashRequest(final Dialog dialog, BGetCashRecord cashRecord, boolean isPass) {
        String url = "";
        if(isPass) {
            url = AppConst.Profit_Commit_Url + "?uniqueId=" + cashRecord.getUnique_id() + "&status=" + 1;
        }else {
            url = AppConst.Profit_Commit_Url + "?uniqueId=" + cashRecord.getUnique_id() + "&status=" + (-1) + "&text="
                    + URLEncoder.encode(mTextReason.getText().toString());
        }

        RequestUtils.getRequest(url, new IHttpResponse() {
            @Override
            public void OnHttpData(final String data) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try{
                            JSONObject object = new JSONObject(data);
                            if(object.getInt("status") != 0) {
                                //失败
                                Toast.makeText(getApplicationContext(),object.getString("msg"),Toast.LENGTH_SHORT).show();
                                return;
                            }
                            Toast.makeText(getApplicationContext(),"提交成功",Toast.LENGTH_SHORT).show();
                            requestGetCashRecordByUser();
                            dialog.dismiss();
                        }catch (Exception e) {
                            Toast.makeText(getApplicationContext(),e.toString(),Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }

            @Override
            public void OnHttpDataError(final IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),e.toString(),Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    private class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {

        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new MyViewHolder(LayoutInflater.from(ProfitActivity.this)
                    .inflate(R.layout.layout_cash_history_recycler_item,parent,false));
        }

        @Override
        public void onBindViewHolder(final MyViewHolder holder, int position) {
            final BGetCashRecord cashRecord = mDataList.get(position);
            if(cashRecord == null) return;
            holder.viewReject.setVisibility(View.GONE);
            holder.viewEndTime.setVisibility(View.VISIBLE);
            holder.viewBtn.setVisibility(View.GONE);
            holder.textUniqueId.setText(cashRecord.getUnique_id());
            if(cashRecord.getStatus() == 0) {
                holder.textStatus.setText("申请中");
                holder.textStatus.setTextColor(Color.parseColor("#aaaaaa"));
                holder.viewEndTime.setVisibility(View.GONE);
                holder.viewBtn.setVisibility(View.VISIBLE);
            }else if(cashRecord.getStatus() == 1) {
                holder.textStatus.setText("通过");
                holder.textStatus.setTextColor(Color.parseColor("#00ff00"));
            }else if(cashRecord.getStatus() == -1) {
                holder.textStatus.setText("未通过");
                holder.textStatus.setTextColor(Color.parseColor("#ff0000"));
                holder.textReject.setText(cashRecord.getReject_text());
                holder.viewReject.setVisibility(View.VISIBLE);
            }
            holder.textStartTime.setText(cashRecord.getStart_time());
            holder.textEndTime.setText(cashRecord.getEnd_time());
            String strMoney = cashRecord.getMoney() + "(元)";
            if(cashRecord.getMoney() != cashRecord.getReal_money()) {
                //审核成功
                strMoney = cashRecord.getReal_money() + "(元)";
                strMoney += "（原申请金额：" + cashRecord.getMoney() + "元" + ",因余额不匹配原金额）";
            }
            holder.textMoney.setText(strMoney);
            holder.textAccount.setText(cashRecord.getAccount() + "(" + cashRecord.getType_name() + ")");
            holder.btnUniqueIdCopy.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ClipboardManager mClipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                    ClipData clipData = ClipData.newPlainText("unique_id", holder.textUniqueId.getText().toString());
                    mClipboardManager.setPrimaryClip(clipData);
                    Toast.makeText(getApplicationContext(),"账号已复制",Toast.LENGTH_SHORT).show();
                }
            });
            holder.btnAccountCopy.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ClipboardManager mClipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                    ClipData clipData = ClipData.newPlainText("unique_id", cashRecord.getAccount());
                    mClipboardManager.setPrimaryClip(clipData);
                    Toast.makeText(getApplicationContext(),"账号已复制",Toast.LENGTH_SHORT).show();
                }
            });
            holder.textUserName.setText(cashRecord.getUser_name());
            holder.textRequest.setText(cashRecord.getRequest_text());
            holder.btnReject.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    showRejectDialog(cashRecord);
                }
            });
            holder.btnPass.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    showPassDialog(cashRecord);
                }
            });
        }

        @Override
        public int getItemCount() {
            return mDataList.size();
        }
    }

    /**
     * 显示提交申请dialog
     */
    private void showRejectDialog(final BGetCashRecord bGetCashRecord) {
        if(mPreCashRecord != null && !mPreCashRecord.getUser_name().equals(bGetCashRecord.getUser_name())) {
            mTextReason.setText("");
        }
        mPreCashRecord = bGetCashRecord;
        if(mRejectDialog == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            View rootView = LayoutInflater.from(this).inflate(R.layout.layout_dialog_reject,null);
            mTextReason = rootView.findViewById(R.id.text_reason);
            Button btnCancel = rootView.findViewById(R.id.btn_cancel);
            Button btnCommit = rootView.findViewById(R.id.btn_commit);
            btnCancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mRejectDialog.dismiss();
                }
            });
            btnCommit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    requestCommitCashRequest(mRejectDialog,bGetCashRecord,false);
                }
            });

            builder.setTitle("拒绝提现");
            builder.setView(rootView);
            mRejectDialog = builder.create();
            mRejectDialog.setCanceledOnTouchOutside(false);
        }
        mRejectDialog.show();
    }

    /**
     * 显示提交申请dialog
     */
    private void showPassDialog(final BGetCashRecord bGetCashRecord) {
        mPreCashRecord = bGetCashRecord;
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("通过")
                .setMessage("确定通过本次提现吗？")
                .setPositiveButton("通过", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        requestCommitCashRequest((Dialog) dialogInterface,bGetCashRecord,true);
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                });
        builder.create().show();
    }
}
